<template>
  <div class="home-wrap">
    <div class="page-left">
      <div class="content-common page-content">
        <div class="search-top">
          <el-form :label-position="'top'" :inline="true" :model="query">
            <el-form-item label="月份">
              <el-date-picker v-model="query.month" format="YYYY-MM" value-format="YYYY-MM" type="month" placeholder="选择月"> </el-date-picker>
            </el-form-item>
            <el-form-item class="search-btn">
              <el-button
                class="table-btn-blur"
                @click="
                  page.currentPage = 1;
                  calenderDate = query.month;
                  getData();
                  getDailyRainfall();
                "
                >查询</el-button
              >
            </el-form-item>
          </el-form>
          <div class="search-btn-title">
            <span class="titleName">{{ currentStnm }}（{{ query.userName }}）</span>
          </div>
          <div class="right-search">
            <el-button class="table-btn-plain" @click="goback()">返回</el-button>
            <el-button class="table-btn-blur" @click="handlerExcelDownLoad">Excel导出</el-button>
          </div>
        </div>
        <el-table :data="tableData" border class="table-common" header-cell-class-name="table-header">
          <el-table-column type="index" width="55" label="序号"></el-table-column>
          <!-- <el-table-column align="center" prop="userName" label="人员姓名"></el-table-column>
            <el-table-column align="center" prop="stnm" label="测站"></el-table-column> -->
          <el-table-column align="center" prop="specificDate" label="日期"></el-table-column>
          <el-table-column align="center" prop="weekDay" label="星期"></el-table-column>
          <el-table-column align="center" prop="recordType" label="打卡类型">
            <template #default="scope">
              <span v-if="scope.row.recordType == 1">工作</span>
              <span v-if="scope.row.recordType == 2">出差</span>
              <span v-if="scope.row.recordType == 3">请假</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="clockInTime" label="上班打卡时间"></el-table-column>
          <el-table-column align="center" prop="clockOffTime" label="下班打卡时间"></el-table-column>
          <el-table-column align="center" prop="coordinate" label="签到点位"></el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template #default="scope">
              <span v-if="scope.row.status == '正常' && isCheckdata" style="color: #00b600">正常</span>
              <span v-else-if="scope.row.status !== '正常' && isCheckdata" style="color: #ee5148">{{ scope.row.status }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center" v-if="isCheckdata">
            <template #default="scope">
              <el-button type="danger" class="table-btn-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="end" style="margin-top: 20px">
          <el-pagination background v-model:currentPage="page.currentPage" @current-change="handlePageChange" layout="prev,total, pager, next" :total="page.totalSize"> </el-pagination>
        </el-row>
      </div>
    </div>
    <div class="page-right">
      <div class="content-common page-content calender-wrap">
        <el-calendar v-model="calenderDate">
          <template #date-cell="{ data }">
            <div class="day-wrapper" :class="holidays.includes(data.day) ? 'holiday' : supplementaries.includes(data.day) ? 'supplementaries' : ''">
              <div class="mark" style="">
                <!-- 左侧显示考勤情况 -->
                <div class="mark-left">
                  <template v-if="!moment(data.day).isAfter(moment())">
                    <template v-if="!holidays.includes(data.day)">
                      <template v-if="supplementaries.includes(data.day)">
                        <template v-if="workMaps[data.day]">
                          <template v-if="!workMaps[data.day].status">
                            <div v-if="workMaps[data.day].remark.includes('正常')" style="background: #00b600">正常</div>
                            <!-- <div v-else style="background: #00b600">正常</div> -->
                          </template>
                          <div v-else-if="workMaps[data.day].status.includes('早退') && isCheckdata" style="background-color: #ff544e">退</div>
                          <div v-else-if="workMaps[data.day].status.includes('迟到') && isCheckdata" style="background-color: #ff544e">迟</div>
                        </template>
                      </template>
                      <!-- 周末不打卡也显示正常 -->
                      <div style="background: #00b600" v-else-if="moment(data.day).day() == 0 || moment(data.day).day() == 6"></div>
                      <template v-else-if="workMaps[data.day]">
                        <template v-if="!workMaps[data.day].status">
                          <div v-if="workMaps[data.day].remark.includes('正常')" style="background: #00b600">正常</div>
                          <div v-if="workMaps[data.day].recordType == 2" style="background: #785fc1">差</div>
                          <div v-if="workMaps[data.day].recordType == 3" style="background: #785fc1">假</div>
                        </template>
                        <template v-else>
                          <div v-if="workMaps[data.day]?.status?.includes('退') && isCheckdata" style="background-color: #ff544e">退</div>
                          <div v-if="workMaps[data.day]?.status?.includes('迟') && isCheckdata" style="background-color: #ff544e">迟</div>
                        </template>
                      </template>
                      <div v-else style="background-color: #ff842f">缺</div>
                    </template>
                  </template>
                </div>
                <!-- 右侧显示节假日信息 -->
                <div class="mark-right">
                  <div>
                    <div v-if="holidays.includes(data.day)" style="background: linear-gradient(135deg, #3f8cff 0%, #72bb57 100%)">休</div>
                    <div v-if="supplementaries.includes(data.day)" style="background-color: #333648">班</div>
                  </div>

                  <div v-if="rainfallMap[data.day]" style="background-color: #10c106">雨</div>
                </div>
              </div>
              <div class="spandate">{{ data.day.split('-').slice(2).join('-') }}</div>
            </div>
          </template>
        </el-calendar>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import {
  sysdictviewlistDictItem,
  getDailyRainfall, //获取月度日降雨
  delAttendanceRecord, //删除打卡记录
  getAttendanceCalendar, //列表查询
  listHolidays //查询当月节假日
} from '../../../api/index';
import moment from 'moment';
export default {
  name: 'zhengbianguancao',
  data() {
    return {
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        month: ''
      },
      formInline: {},
      tableData: [],
      pageTotal: 0,
      stationData: [],
      checkArr: [],
      startTimeOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      isView: false,
      calenderDate: new Date(),
      activeday: [],
      holidays: [],
      supplementaries: [],
      moment,
      workMaps: {},
      isCheckdata: false, //roleNoList中包含JS-00000007为审批人员
      currentStnm: '', //当前所属测站
      rainfallMap: {}
    };
  },
  watch: {
    // calenderDate(newVal, oldVal) {
    //   // 格式化 因为绑定的数组不是我们想用的，这里以2022-22-22这种格式作为演示
    //   let date = this.formatDate(newVal);
    //   this.query.specificDate = date;
    //   // 这里就是我们处理数据，调用接口的位置
    //   this.getData('calender');
    // }
  },
  created() {
    let roleCode = JSON.parse(sessionStorage.getItem('userInfo')).roleNoList.join(',');
    if (roleCode.indexOf('JS-00000007') > -1) {
      this.isCheckdata = true;
    } else {
      this.isCheckdata = false;
    }
    this.query = this.$route.query;
    this.query.month = this.formatMonth(this.query.specificDate);
    this.globalUser = globalUser;
    this.getData();
    this.getDailyRainfall();
  },
  methods: {
    //获取月度日降雨
    getDailyRainfall() {
      // 清空雨量数据
      // this.rainfallMap = {};
      if (this.query.stcd) {
        const currentMonth = moment(this.calenderDate).format('YYYY-MM');
        // 获取当月雨量
        getDailyRainfall({
          stType: this.query.stType,
          stcd: this.query.stcd,
          yearMonth: currentMonth
        }).then((res) => {
          res.object.map((item) => {
            if (item.drp > 0) {
              this.rainfallMap[item.tm] = item.drp;
            }
          });
        });
      }
    },
    // 改变当前页面
    handlePageChange(page) {
      this.currentPage = page;
    },
    formatMonth(date) {
      const value = new Date(date);
      const year = value.getFullYear();
      const month = (value.getMonth() + 1).toString().padStart(2, '0');
      return `${year}-${month}`;
    },
    formatDate(date) {
      const value = new Date(date);
      const year = value.getFullYear();
      const month = (value.getMonth() + 1).toString().padStart(2, '0');
      const day = value.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    //导出
    async handlerExcelDownLoad() {
      let url = globalVar.xiaoliuyubaseURL + '/soilWater/manage/attendance/export/exportAttendanceRecord';
      var options = {
        url: url,
        method: 'post',
        responseType: 'blob',
        headers: {
          Authorization: sessionStorage.getItem('token')
        }
      };
      axios(options).then((res) => {
        if (res) {
          const link = document.createElement('a');
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }); //生成blob对象
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          const fileName = '考勤打卡记录表';
          link.setAttribute('download', `${fileName}` + '.xlsx'); //下载的文件名以及文件格式
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          console.log('下载失败');
        }
      });
    },
    async getData(source) {
      const currentMonth = moment(this.calenderDate).format('YYYY-MM');
      // 假日
      this.holidays = [];
      // 补班
      this.supplementaries = [];
      const prevMonth = moment(this.calenderDate).startOf('month').subtract(1, 'months').format('YYYY-MM');
      const nextMonth = moment(this.calenderDate).startOf('month').subtract(-1, 'months').format('YYYY-MM');
      // 上个月假期
      const prevHoliday = await listHolidays({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: prevMonth
      });
      if (prevHoliday.code == 1) {
        Object.keys(prevHoliday.object).map((key) => {
          const current = prevHoliday.object[key];
          if (current.holiday) {
            this.holidays.push(current.date);
          } else {
            this.supplementaries.push(current.date);
          }
        });
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      // 本月假期
      const currentHoliday = await listHolidays({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: currentMonth
      });
      if (currentHoliday.code == 1) {
        Object.keys(currentHoliday.object).map((key) => {
          const current = currentHoliday.object[key];
          if (current.holiday) {
            this.holidays.push(current.date);
          } else {
            this.supplementaries.push(current.date);
          }
        });
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      // 下个月假期
      const nextHoliday = await listHolidays({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: nextMonth
      });
      if (nextHoliday.code == 1) {
        Object.keys(nextHoliday.object).map((key) => {
          const current = nextHoliday.object[key];
          if (current.holiday) {
            this.holidays.push(current.date);
          } else {
            this.supplementaries.push(current.date);
          }
        });
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      // 获取上月的考勤记录
      const prevRecord = await getAttendanceCalendar({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: prevMonth
      });
      if (prevRecord.code == 1) {
        const tableData = prevRecord.object;
        for (let i = 0; i < tableData.length; i++) {
          const current = tableData[i];
          this.workMaps[current.specificDate] = { ...current };
        }
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      // 获取本月的考勤记录
      const currentRecord = await getAttendanceCalendar({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: currentMonth
      });
      if (currentRecord.code == 1) {
        // 清空数据
        this.tableData = [];
        const tableData = currentRecord.object;
        for (let i = 0; i < tableData.length; i++) {
          const current = tableData[i];
          this.workMaps[current.specificDate] = { ...current };
          if (current.status == null || current.status == '') {
            current.status = '正常';
          }
          if (current.userName == null || current.userName == '') {
            current.userName = this.query.userName;
          }
          this.tableData[i] = current;
        }
        this.currentStnm = this.tableData.length ? this.tableData[0].stnm : '';
        this.page.totalSize = currentRecord.object.length;
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      // 获取下月的考勤记录
      const nextRecord = await getAttendanceCalendar({
        currentPage: 1,
        pageSize: 100,
        userCode: this.query.userCode,
        yearMonth: nextMonth
      });
      if (nextRecord.code == 1) {
        const tableData = nextRecord.object;
        for (let i = 0; i < tableData.length; i++) {
          const current = tableData[i];
          this.workMaps[current.specificDate] = { ...current };
        }
      } else {
        this.$message.error('系统错误，请联系管理员');
      }
      this.$forceUpdate();
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          delAttendanceRecord({
            id: row.id
          }).then((e) => {
            this.$message.success('删除成功');
            this.getData();
          });
        })
        .catch(() => {});
    },
    goback() {
      this.$router.push({
        path: 'examSituationManagement'
      });
    }
  }
};
</script>

<style lang="less" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.table-btn-plain {
  background: #fff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #3f8cff !important;
  font-size: 14px;
}
.search-btn {
  margin-top: 30px;
  width: auto !important;
}
.table-btn-blur {
  background: #3f8cff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-delete {
  background: #ff544e !important;
  border: 1px solid #ff544e !important;
  border-radius: 2px;
  color: #fff !important;
}
.content-common {
}

.home-wrap {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  position: relative;
  width: 100%;
  overflow-x: hidden;
  min-width: 1280px;
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  .page-left {
    width: calc(100% - 520px);
    min-width: 800px;
  }
  .page-right {
    width: 520px;
  }
  .page-content {
    height: calc(100% - 60px);
  }
}
::v-deep .el-table .cell {
  word-break: keep-all;
}
::v-deep .el-calendar {
  padding-right: 17px;
  // 隐藏切换按钮
  .el-calendar__button-group {
    visibility: hidden;
  }
  .el-calendar__header {
    font-size: 16px;
    font-weight: 700;
    color: #000000;
    line-height: 22px;
    border-bottom: 0;
  }
  .el-calendar__body {
    padding: 0px 0px 30px;
    user-select: none;
    .el-calendar-table {
      user-select: none;
    }
    thead {
      th {
        color: #00041a;
        font-weight: 600;
        font-size: 18px;
        border-bottom: 2px solid #ebebeb;
      }
    }
    .el-calendar-table__row {
      td {
        border: 0;
        height: unset;
        border-radius: 50%;
        font-size: 18px;
        font-weight: 600;
        height: 111px;
        width: 12px;
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        &.is-today,
        &.is-selected {
          .day-wrapper {
            background: #5190f5;
            color: #fff;
          }
        }
        &.is-selected .day-wrapper {
          background: #5190f5 !important;
          color: #fff !important;
        }
        &.prev,
        &.next {
          .spandate {
            color: rgba(0, 4, 26, 0.5);
          }
          .day-wrapper {
            &:hover {
              background-color: #fff;
            }
          }
          &.is-today {
            .day-wrapper {
              background-color: rgba(0, 4, 26, 0.1);
              .spandate {
                color: #000;
              }
            }
          }
        }
      }
      .el-calendar-day {
        height: 100%;
        width: 100%;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0;
        position: relative;
        // 单项包裹
        .mark {
          width: 54px;
          height: 54px;
          position: absolute;
          box-sizing: content-box;
          left: -4px;
          top: -4px;
          line-height: 20px;
          display: flex;
          // flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;
          font-size: 14px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          line-height: 16px;
          .mark-left {
            height: 100%;
          }
          .mark-right {
            height: 100%;
            color: #fff;
          }
          .mark-left,
          .mark-right {
            display: flex;
            justify-content: space-between;
            flex-direction: column;
            align-items: flex-start;
          }
          div > div {
            padding: 0 1px;
          }
        }
        .day-wrapper {
          position: relative;
          background-color: #fff;
          display: inline-block;
          width: 46px;
          height: 46px;
          line-height: 46px;
          text-align: center;
          border-radius: 14px;
          font-size: 18px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          color: #00041a;
          user-select: none;
          &:hover {
            background-color: #eef4fe;
            color: #152432;
          }
          &.holiday {
            background: linear-gradient(135deg, #3f8cff6f 0%, #72bb572a 100%);
            color: #00041a;
          }
          &.supplementaries {
            background: rgba(0, 4, 26, 0.1);
          }
        }
        span {
          height: 46px;
          line-height: 46px;
          width: 46px;
          text-align: center;
          border-radius: 50%;
          display: inline-block;
        }
        &:hover {
          background-color: unset;
          span {
            width: 46px;
            height: 46px;
            border-radius: 14px;
            background-color: #eef4fe;
            color: #00041a;
          }
        }
      }
      .is-selected {
        background-color: unset;
        .el-calendar-day {
          span {
            width: 46px;
            height: 46px;
            background: #5190f5;
            border-radius: 14px;
            color: #ffffff;
          }
        }
      }
    }
  }
  .is-point {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: center;
    margin: 0;
    i {
      margin-top: 1px;
      display: inline-block;
      width: 6px;
      height: 6px;
      background: #ff0000;
      border-radius: 50%;
    }
  }
}
.activeContent {
  width: 46px;
  height: 46px;
  background: #e15832;
  border-radius: 14px;
  color: #ffffff;
  margin-top: -98px;
  margin-left: -10px;
}
.titleName {
  font-size: 22px;
  font-weight: 600;
}
.search-btn-title {
  position: relative;
  display: flex;
  justify-content: center;
  top: -34px;
}
</style>

